package cn.zh.npro.Fragment;

import android.app.Dialog;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;

import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cn.zh.npro.Adapter.HFAdapter;
import cn.zh.npro.Item.HFItem;
import cn.zh.npro.MyApplication;
import cn.zh.npro.R;
import cn.zh.npro.Util.BaseUrl;
import cn.zh.npro.Util.Loading;
import cn.zh.npro.Util.MyMarkerView;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by WYN on 2018/2/28 0028.
 */

public class HMoney extends Fragment {
    LineChart dlineChart,mlineChart,ylineChart;
    RadioButton txtd,txtm,txty;
    ListView hflist;
    HFAdapter hfAdapter=null;
    ArrayList<HFItem> hfItems=new ArrayList<HFItem>();
    TextView hdata,hfhtype,hgra;
    RadioGroup dtgroup;
    TextView hmempty;
    private Dialog LDialog;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
         View view=LayoutInflater.from(getActivity()).inflate(R.layout.hm_layout,null,false);
         inithf(view);
         getGetTradeReport("day");
         getGetTradeRepor("day");
         getGetTradeRepor("month");
         getGetTradeRepor("year");
         return view;
         }


    private void inithf(View view){
        hmempty=view.findViewById(R.id.hmempty);
        dlineChart=view.findViewById(R.id.dlinechart);
        mlineChart=view.findViewById(R.id.mlinechart);
        ylineChart=view.findViewById(R.id.ylinechart);
        hflist=view.findViewById(R.id.hflist);
        hdata = view.findViewById(R.id.hdata);
        hfhtype = view.findViewById(R.id.hfhtype);
        hgra = view.findViewById(R.id.hgra);
        hfhtype.setText("订单金额");
        hfhtype=view.findViewById(R.id.hfhtype);
        hfAdapter=new HFAdapter(getActivity(),hfItems,0);
        hflist.setAdapter(hfAdapter);
        txtd=view.findViewById(R.id.txtd);
        txtm=view.findViewById(R.id.txtm);
        txty=view.findViewById(R.id.txty);
        txtd.setTextColor(getResources().getColor(R.color.white));
        txtd.setBackgroundDrawable(getResources().getDrawable(R.drawable.dbg));
        dtgroup=view.findViewById(R.id.dtgroup);
        dtgroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                inittxt();
                switch (i){
                    case R.id.txtd:
                        hgra.setText("与上日环比");
                        txtd.setTextColor(getResources().getColor(R.color.white));
                        txtd.setBackgroundDrawable(getResources().getDrawable(R.drawable.dbg));
                         getGetTradeReport("day");
                        break;
                    case R.id.txtm:
                        hgra.setText("与上月环比");
                        txtm.setTextColor(getResources().getColor(R.color.white));
                        txtm.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                        getGetTradeReport("month");
                        break;
                    case R.id.txty:
                        hgra.setText("与上年环比");
                        txty.setTextColor(getResources().getColor(R.color.white));
                        txty.setBackgroundDrawable(getResources().getDrawable(R.drawable.ybg));
                        getGetTradeReport("year");
                        break;
                     }
                    }
                 });
            }





    private void initLineChart(LineChart mLineChart, final ArrayList<String> strings, ArrayList<Float> floats){

        List<Entry> entries = new ArrayList<>();
        entries.clear();
        for (int i = 0; i < floats.size(); i++) {
            float data = floats.get(i);
            entries.add(new Entry(data, i));
           }

        LineDataSet dataSet = new LineDataSet(entries, "");
        dataSet.setColor(Color.parseColor("#45a6d9"));// 每个点之间线的颜色，还有其他几个方法，自己看

        ArrayList<ILineDataSet> lineDataSets = new ArrayList<ILineDataSet>();
        lineDataSets.add(dataSet); // add the datasets

        LineData lineData = new LineData(strings,lineDataSets);
        lineData.setValueTextSize(15);
        dataSet.setLineWidth(2.0f);
        dataSet.setCircleSize(4f);
        dataSet.setColor(Color.parseColor("#3498DB"));
        dataSet.setCircleColor(Color.parseColor("#3498DB"));
        dataSet.setCircleColorHole(Color.parseColor("#3498DB"));

        mLineChart.setDescription(null);
        lineData.setDrawValues(false);
        mLineChart.setBackgroundColor(Color.WHITE);
        mLineChart.setNoDataText("暂无数据");
        mLineChart.setDrawGridBackground(true);
        mLineChart.setGridBackgroundColor(Color.WHITE);
        mLineChart.setDrawBorders(false);
        mLineChart.setTouchEnabled(true);
        mLineChart.setDragEnabled(true);
        mLineChart.setScaleEnabled(true);
        mLineChart.setScaleXEnabled(true);
        mLineChart.setScaleYEnabled(false);
        mLineChart.setPinchZoom(true);
        mLineChart.setDoubleTapToZoomEnabled(false);
        mLineChart.setDragDecelerationEnabled(true);
        mLineChart.setDragDecelerationFrictionCoef(0.9f);
        dataSet.setHighlightEnabled(true);
        dataSet.setDrawHighlightIndicators(false);
        XAxis xAxis = mLineChart.getXAxis();
        YAxis yAxis = mLineChart.getAxisLeft();
        mLineChart.getAxisRight().setEnabled(false);
        float ratio = (float) strings.size()/(float) 6;
        mLineChart.zoom(ratio,1f,0,0);
        mLineChart.animateX(1500);
        yAxis.setAxisLineColor(Color.WHITE);
        xAxis.setDrawGridLines(false);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        yAxis.setLabelCount(3, false);
        yAxis.setAxisMinValue(0);
        Legend l = mLineChart.getLegend();
        l.setEnabled(false);
        mLineChart.setMarkerView(new MyMarkerView(getActivity(), R.layout.custom_marker_view));    // 点击数据点显示的pop，有俩默认的，MarkerImage：一张图片，MarkerView:一个layout布局,也可以自己定义.这里这个是我自定义的一个MarkerView。
        mLineChart.setData(lineData);
        if (mLineChart.getData().getYMax()==0){
            mLineChart.getAxisLeft().setAxisMaxValue(20f);
            mLineChart.notifyDataSetChanged();
           }
         }



    public void inittxt(){
        txtd.setTextColor(getResources().getColor(R.color.colorPrimary));
        txtm.setTextColor(getResources().getColor(R.color.colorPrimary));
        txty.setTextColor(getResources().getColor(R.color.colorPrimary));
        txtd.setBackgroundDrawable(getResources().getDrawable(R.drawable.wdbg));
        txtm.setBackgroundDrawable(getResources().getDrawable(R.drawable.rmbg));
        txty.setBackgroundDrawable(getResources().getDrawable(R.drawable.wybg));
         }

    //获取订单金额报表
    public void getGetTradeReport(final String type){
        MyApplication mapp= (MyApplication)getActivity(). getApplication();
        SharedPreferences sp = mapp.getSp();
        LDialog= Loading.createLoadingDialog(getActivity(),"加载中...");
        OkHttpUtils.get(BaseUrl.GetTradeReport+"?UserId="+ sp.getString("uid",""))
                .params("type",type)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        Loading.closeDialog(LDialog);
                        try {
                            JSONObject js=new JSONObject(s);
                            boolean State=js.getBoolean("State");
                            hfItems.clear();
                            if (State){
                                JSONArray Res=js.getJSONArray("Res");
                                for (int i=0;i<Res.length();i++){
                                 JSONObject ji=Res.getJSONObject(i);
                                 double GoodsTotal=ji.getDouble("GoodsTotal");
                                 double GoodsTotal1=ji.getDouble("GoodsTotal1");
                                 String SndTime=ji.getString("SndTime");
                                    String str;
                                 if (type.equals("year")){
                                     str=SndTime.substring(SndTime.length()-4);
                                 }else {
                                     str = SndTime.substring(SndTime.length()-2);
                                   }
                                 HFItem hfItem=new HFItem(SndTime,GoodsTotal,GoodsTotal1);
                                 hfItems.add(hfItem);
                                 }
                                hfAdapter.notifyDataSetChanged();

                                if (hfItems.size()==0){
                                    dlineChart.setVisibility(View.GONE);
                                    mlineChart.setVisibility(View.GONE);
                                    ylineChart.setVisibility(View.GONE);
                                    hmempty.setVisibility(View.VISIBLE);
                                }else {
                                    hmempty.setVisibility(View.GONE);
                                    switch (type){
                                        case "day":
                                            mlineChart.setVisibility(View.GONE);
                                            ylineChart.setVisibility(View.GONE);
                                            dlineChart.setVisibility(View.VISIBLE);
                                            break;
                                        case "month":
                                            dlineChart.setVisibility(View.GONE);
                                            ylineChart.setVisibility(View.GONE);
                                            mlineChart.setVisibility(View.VISIBLE);
                                            break;
                                        case "year":
                                            dlineChart.setVisibility(View.GONE);
                                            mlineChart.setVisibility(View.GONE);
                                            ylineChart.setVisibility(View.VISIBLE);
                                            break;
                                    }
                                }

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                         }
                        }
                     });
                   }



    //获取订单金额报表
    public void getGetTradeRepor(final String type){
        MyApplication mapp= (MyApplication)getActivity(). getApplication();
        SharedPreferences sp = mapp.getSp();
        OkHttpUtils.get(BaseUrl.GetTradeReport+"?UserId="+ sp.getString("uid",""))
                .params("type",type)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        try {
                            JSONObject js=new JSONObject(s);
                            boolean State=js.getBoolean("State");
                            if (State){
                                JSONArray Res=js.getJSONArray("Res");
                                ArrayList<String>date=new ArrayList<>();
                                ArrayList<Float> score= new ArrayList<>();
                                for (int i=0;i<Res.length();i++){
                                    JSONObject ji=Res.getJSONObject(i);
                                    double GoodsTotal=ji.getDouble("GoodsTotal");
                                    String SndTime=ji.getString("SndTime");
                                    String str;
                                    if (type.equals("year")){
                                        str=SndTime.substring(SndTime.length()-4);
                                    }else {
                                        str = SndTime.substring(SndTime.length()-2);
                                    }
                                    date.add(str);
                                    score.add((float)GoodsTotal);
                                   }
                                switch (type){
                                    case "day":
                                        if (score.size()==0){
                                            hmempty.setVisibility(View.VISIBLE);
                                            dlineChart.setVisibility(View.GONE);
                                        }else {
                                            hmempty.setVisibility(View.GONE);
                                            dlineChart.setVisibility(View.VISIBLE);
                                            initLineChart(dlineChart,date,score);
                                           }
                                        break;
                                    case "month":
                                        initLineChart(mlineChart,date,score);
                                        break;
                                    case "year":
                                        initLineChart(ylineChart,date,score);
                                        break;
                                  }
                            }else {
                               dlineChart.setVisibility(View.GONE);
                               mlineChart.setVisibility(View.GONE);
                               ylineChart.setVisibility(View.GONE);
                               hmempty.setVisibility(View.VISIBLE);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                     }
                });
               }



      }
